package com.jekunauto.retrofittest;

import android.annotation.SuppressLint;

import com.jekunauto.retrofittest.证书相关.TrustAllHostnameVerifier;
import com.jekunauto.retrofittest.证书相关.TrustAllManager;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 用户请求
 */

public class AppClientTwo {
    static Retrofit mRetrofit;

    public static Retrofit retrofit() {
        if (mRetrofit == null) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(15, TimeUnit.SECONDS)//连接超时(单位:秒)
                    .writeTimeout(20, TimeUnit.SECONDS)//写入超时(单位:秒)
                    .readTimeout(20, TimeUnit.SECONDS)//读取超时(单位:秒)
                    .pingInterval(20, TimeUnit.SECONDS) //websocket轮训间隔(单位:秒)
                    // .cache(new Cache(cache.getAbsoluteFile(), cacheSize))//设置缓存
                    // .cookieJar(cookieJar)//Cookies持久化
                    .sslSocketFactory(createSSLSocketFactory())//https配置
                    .hostnameVerifier(new TrustAllHostnameVerifier())
                    .build();
            mRetrofit = new Retrofit.Builder()
                    .baseUrl("https://weqxin.com/api/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(okHttpClient)
                    .build();
        }
        return mRetrofit;
    }

    /**
     * 信任所有证书
     *
     * @return
     */
    @SuppressLint("TrulyRandom")
    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory sSLSocketFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllManager()},
                    new SecureRandom());
            sSLSocketFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return sSLSocketFactory;
    }
}
